package org.iabako.client.ui.form.user.userconfiguration;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.HTMLPanel;
import org.iabako.client.config.page.PageConfigEnum;
import org.iabako.client.config.page.PageTagItemEnum;
import org.iabako.client.ui.form.AbstractForm;
import org.iabako.client.ui.layout.field.IField;
import org.iabako.client.ui.layout.template.Popup;
import org.iabako.client.ui.layout.template.PopupTagItem;
import org.iabako.client.user.AuthenticateUserProvider;
import org.iabako.shared.entity.business.AbstractEntity;
import org.iabako.shared.entity.user.User;
import org.iabako.shared.exception.IabakoActionForbiddenException;
import org.iabako.shared.iservice.user.UserServiceAsync;

import java.util.List;

/**
 * Created by jose on 24/09/14.
 */
public abstract class UsersConfigurationForm extends AbstractForm {

    interface MyUiBinder extends UiBinder<HTMLPanel, UsersConfigurationForm> {
    }

    protected MyUiBinder binderForm = GWT.create(MyUiBinder.class);

    protected final UserServiceAsync userServiceAsync = UserServiceAsync.Util.getInstance();

    @UiField
    MyUserForm myUserForm;
    @UiField
    UsersForm usersForm;

    public UsersConfigurationForm(PageConfigEnum accountConfiguration, String explanationLabel) throws IabakoActionForbiddenException {

        if (AuthenticateUserProvider.getUser().getEnterprise().isDemo()) {
            throw new IabakoActionForbiddenException("action_disable_for_demo_title", "action_disable_for_demo_text", true);
        }

        setForm(binderForm, accountConfiguration, explanationLabel);

        for (final PopupTagItem popupTagItem : popup.popupTagItems.keySet()) {
            switch (popupTagItem.pageTagItemEnum) {
                case MyUser:
                    popup.popupTagItems.put(popupTagItem, myUserForm);
                    break;
                case Users:
                    if (AuthenticateUserProvider.getUser().isLimitedVisibility()) {
                        popupTagItem.setVisible(false);
                    } else {
                        popup.popupTagItems.put(popupTagItem, usersForm);
                        popupTagItem.setAbstractForm(usersForm);
                    }
                    break;
            }
        }
        popup.setSelectedTag(PageTagItemEnum.MyUser);
        Popup.resizeToMediumPopup();
    }

    @Override
    protected List<IField> getMandatoryFields() {
        return myUserForm.getMandatoryFields();
    }

    @Override
    protected AbstractEntity getEntity() {
        return null;
    }

    @Override
    public boolean validate() {
        boolean myUserFormValidate = myUserForm.validate();

        if (!myUserFormValidate) {
            return false;
        }

        userServiceAsync.save((User) myUserForm.getEntity(), myUserForm.getNewSaveUserHandler(this));

        return true;
    }
}
